﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gaf.Impl.Activators
{
    internal class GafServiceCollection : IServiceCollection
    {
        private readonly IServiceCollection _inner;

        private readonly List<ServiceDescriptor> _addinServices;

        public GafServiceCollection(IServiceCollection services, List<ServiceDescriptor> addinServices)
        {
            _inner = services;
            _addinServices = addinServices;
        }

        ServiceDescriptor IList<ServiceDescriptor>.this[int index] { get => _inner[index]; set => _inner[index] = value; }

        int ICollection<ServiceDescriptor>.Count => _inner.Count;

        bool ICollection<ServiceDescriptor>.IsReadOnly => _inner.IsReadOnly;

        void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item)
        {
            _inner.Add(item);
            _addinServices.Add(item);
        }
        void IList<ServiceDescriptor>.Insert(int index, ServiceDescriptor item)
        {
            _inner.Insert(index, item);
            _addinServices.Add(item);
        }

        void ICollection<ServiceDescriptor>.Clear()
        {
            _inner.Clear();
            _addinServices.Clear();
        }
        bool ICollection<ServiceDescriptor>.Remove(ServiceDescriptor item)
        {
            _addinServices.Remove(item);
            return _inner.Remove(item);
        }

        void IList<ServiceDescriptor>.RemoveAt(int index)
        {
            bool canRemove = false;
            for (var i = 0; i < _inner.Count; i++)
            {
                if (i == index)
                {
                    _addinServices.Remove(_inner[i]);
                    canRemove = true;
                }
            }
            if (canRemove) _inner.RemoveAt(index);
        }

        bool ICollection<ServiceDescriptor>.Contains(ServiceDescriptor item) => _inner.Contains(item);

        void ICollection<ServiceDescriptor>.CopyTo(ServiceDescriptor[] array, int arrayIndex) => _inner.CopyTo(array, arrayIndex);

        IEnumerator<ServiceDescriptor> IEnumerable<ServiceDescriptor>.GetEnumerator() => _inner.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => _inner.GetEnumerator();
        int IList<ServiceDescriptor>.IndexOf(ServiceDescriptor item) => _inner.IndexOf(item);




    }
}
